<?php

class DistrictController extends Controller
{
   /**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      //CVarDumper::dump($rights,10,true);die();
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
      
	public function actionIndex()
	{
	     
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $model = new District();
      $total_record = $model->count();
      $list = array();
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      $object = $model->with('province')->findAll(array(
         'order' => 'prv_name ASC',
         'offset' => $start,
         'limit' => $limit,
      ));   
      if(count($object) > 0){
         foreach($object as $item){
            $list[$item->attributes['dis_id']] = $item->attributes;
            $list[$item->attributes['dis_id']]['prv_name'] = !is_null($item->getRelated('province')) ? $item->getRelated('province')->attributes['prv_name'] : "Chưa rõ";
         }
      }
      //CVarDumper::dump($list,10,true);die();
		$this->render('index',array("model" => $model,
                                  "session_user" => $session_user,
                                  "list" => $list,
                                  "rowList" => $rowList,
                                  "page" => $page,
                                  "start" => $start,
                                  "limit" => $limit,
                                  "total_record" => $total_record,
                                  "total_pages" => $total_pages,));
	}
   
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      
      $model = new District();
      $message = '';
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      if(isset($_POST['District'])){
         $model->attributes = $_POST['District'];
         $model->dis_name = ucwords(strtolower($model->dis_name));
         if($model->validate()){
            $model->save();
            $message = 'Thêm mới thành công';
            if($action_user == 'save'){
               $this->redirect('/admin/'.$this->id);
            } 
         }
         //CVarDumper::dump($model->attributes,10,true);die();
      }
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_name ASC'
      ));
      $list_province = array();
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $this->layout = '//layouts/cms/create';
      $this->render('create',array('model' => $model,
                                    'list_province' => $list_province,
                                    'message' => $message));
      
   }
   
   /**
    * 
    * Display page edit
   */
   public function actionEdit(){
      $session_user = Yii::app()->session['session_user'];
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      $id = Yii::app()->request->getParam('id',0);
      $model = District::model()->findByPk($id);
      if(isset($_POST['District'])){
         $model->attributes = $_POST['District'];
         if($model->validate()){
            $message = "Cập nhật thành công";
            $model->save(false);
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }   
         }
      }
      $province = new Province();
      $object = $province->findAll(array(
         'order' => 'prv_name ASC'
      ));
      $list_province = array();
      if(count($object) > 0){
         foreach($object as $item){
            $list_province[$item->attributes['prv_id']] = $item->attributes['prv_name'];
         }
      }
      $this->layout = '//layouts/cms/create';
      $this->render('edit',array('model' => $model,
                                 'list_province' => $list_province,
                                 'session_user' => $session_user,
                                 'message' => $message
                                 ));
      
   }
   
   /**
    * 
    * Get all district by prv_id
   */
   public function actionSetDropListByPrvID($prv_id){
      $option = array(0 => '-- Quận/Huyện --');
      if($prv_id > 0){
         $model = new District();
         $object = $model->findAllByAttributes(array('prv_id' => $prv_id));
         if(count($object) > 0){
            foreach($object as $item){
               $option[$item->attributes['dis_id']] = $item->attributes['dis_name'];
            }
         }
      }
      foreach($option as $key=>$value){
         echo '<option value="'.$key.'">'.$value.'</option>';
      }
   }
   
   
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM district WHERE dis_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}


	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}